package com.mk.wardsystemserver.config;

import com.mk.wardsystemserver.config.security.component.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * WebSocket配置类
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;
    /**
     * 添加这个Endpoints,网页可以通过websocket连接上服务
     * 就是我们配置的websocket的服务地址，并且可以指定是否使用socketJS
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        /**
         *将ws/ep路径注册为stomp端点,用户连接了这个端点可以进行websocket通讯，支持socketJS
         * setAllowedOrigins("*")允许跨域
         * withSockJS()支持socketJS访问
         */
       registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
    }

    /**
     * 不用JWT令牌时不需要配置
     * 输入通道参数配置
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor= MessageHeaderAccessor.getAccessor(message,StompHeaderAccessor.class);
                //获取accessor目的是为了判断是不是连接，
                // 如果是连接就i要获得对应的token，设置到用户对象里面去，如果不是，直接返回
                if(StompCommand.CONNECT.equals(accessor.getCommand())){
                    //获取token -----Auth-Token是前端传过来的
                    String token= accessor.getFirstNativeHeader("Auth-Token");
                    //判断是否拿到的token
                    if(!StringUtils.isEmpty(token)){
                        String authToken=token.substring(tokenHead.length());
                        String username= jwtTokenUtil.getUserNameFromToken(authToken);;
                        //判断用户名是否为空
                        if(!StringUtils.isEmpty(username)){
                            //登录
                            UserDetails userDetails= userDetailsService.loadUserByUsername(username);
                            //判断是否有效,重新设置用户,credentials是凭证一般是密码不需要传设置为空即可
                            if(jwtTokenUtil.validateToken(authToken,userDetails)){
                                UsernamePasswordAuthenticationToken authenticationToken=
                                        new UsernamePasswordAuthenticationToken(userDetails,null,
                                                userDetails.getAuthorities());
                                /*设置用户对象,获取SpringSecurity全局上下文*/
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                accessor.setUser(authenticationToken);
                            }
                        }
                    }
                }
                return message;
            }
        });
    }
    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //配置代理域,可以配置多个，配置代理目的地前缀为/queue,queue随便定义,可以在配置域上向客户端推送消息
       registry.enableSimpleBroker("/queue");
    }
}
